package com.housekeeping.housekeeping.cleanerInformation.controller;

import com.alibaba.fastjson.JSONObject;
import com.housekeeping.housekeeping.cleanerInformation.entity.Cleaner;
import com.housekeeping.housekeeping.cleanerInformation.service.ICleanerService;
import com.housekeeping.housekeeping.cleanerInformation.service.impl.CleanerServiceImpl;
import com.housekeeping.housekeeping.cleanerInformation.utils.ResponseEntity;
import com.housekeeping.housekeeping.cleanerInformation.utils.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author hua
 * @version JDK1.8
 * @date 2021/1/19 11:46
 *      添加
 */
@WebServlet("/cleanerInformation/controller/CleanerInsertController")
public class CleanerInsertController extends HttpServlet {
    private ICleanerService cleanerService = new CleanerServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求字符集
        request.setCharacterEncoding("utf-8");
        //设置响应字符集text/html;charset=utf-8
        response.setContentType("text/html;charset=utf-8");

        String message = "";
        Cleaner cleaner = null;
        ResponseEntity<Object> entity = null;
        if (request.getParameter("message") != null){
            //获取前端发送包含要添加的保洁员信息的json数据
            message = request.getParameter("message");

            //解析json数据
            cleaner = JSONObject.parseObject(message, Cleaner.class);
            entity = null;

            //数据库受影响行数
            int i = 0;
            try {
                i = cleanerService.cleanerInsert(cleaner);
                if (i > 0){
                    entity = ResponseEntity.success(null);
                }else {
                    entity = ResponseEntity.error(401,"添加失败");
                }
            } catch (SQLException throwables) {
                entity = ResponseEntity.error(402,"网络异常,请稍后再试");
            }
            ResponseUtils.resp(response,entity);
        }
    }

}
